import React from  'react'
import { Table,Modal,message,Button,Card,Form ,Input,TreeSelect,Tag,Divider  } from 'antd'
import axios from "../../../axios/axios";
import Utils from './../../../utils/utils'
import BaseFilterForm from './../../../components/BaseFilterForm'

import './../../../style/common.less'

const SHOW_PARENT = TreeSelect.SHOW_PARENT

export default class User extends React.Component{
    state={
        dataSource:[],
        isGrantVisible:false,
        grantData:[],
        value: [],
        treeData:[],
        username:'',
        userId:''
    }

    params = {
        page:1,
        limit:5
    }
    formList = [
        {
            type:'INPUT',
            label:'用户名称',
            field:'name',
            placeholder:'模糊查询用户名'
        },
        {
            type:'DATEPICKER',
            label:'',
            field:'createDateTimeStart',
            field2:'createDatetimeEnd'
        }
    ]
    componentWillMount(){
        this.filterSubmit()
    }

    onChange = (value) => {
        console.log('onChange ', value);
        this.setState({ value });
    }

    handleOperator = (type)=> {
        let rows = this.state.selectedRows
        if(type ==='create'){
            this.setState({
                title:'创建用户',
                isVisible:true,
                type
            })
        }else if(type==="edit" || type==='detail'){
            if (!rows || rows.length>1){
                Modal.warn({
                    title:'警告',
                    content:'只能选中一行进行编辑!'
                })
                return
            }
            this.setState({
                title:type==='edit'?'编辑用户':'查看详情',
                isVisible:true,
                userInfo:rows[0],
                type
            })

        }else if(type ==='delete'){
            // 先进行过滤
            if ( !rows || rows.length ===0){
                Modal.warn({
                    title:'警告',
                    content:'需要至少先选中一行!'
                })
                return
            }
            // 获取ids
            let idList = []
            let usernameList=[]
            rows.map((item) => {
                idList.push(item.id)
                usernameList.push(item.username)
                return item
            })
            let ids=idList.join(",")
            // 进行删除
            Modal.confirm({
                title:`确定要删除:${usernameList.join(',')}用户`,
                okText:'确定',
                onOk:() => {
                    axios.ajax({
                        url:'/cloud-long-upms/sysUser/deleteBatch',
                        method:'delete',
                        data:{
                            params:{
                                ids:ids
                            }
                        }
                    }).then((res)=>{
                        if (res.status===200) {
                            this.setState({
                                isVisible:false
                            })
                            message.info(`${res.message}`)
                            this.requestList()
                        }
                    })
                },
                onCancel:() => {
                    message.info("取消批量删除!")
                },
                cancelText:'取消'
            })
        }
    }

    handleSubmit =()=>{
        let type = this.state.type
        let data =  this.userForm.props.form.getFieldsValue()
        if (type === 'edit'){
            data.id = this.state.selectedRows[0].id
        }
        axios.ajax({
            url:type === 'create'? '/cloud-long-upms/sysUser/add':'/cloud-long-upms/sysUser/update',
            method:type === 'create'? 'post':'put',
            data:{
                params:{
                    ...data
                }
            }
        }).then((res)=>{
            if(res.status ===200){
                this.setState({
                    isVisible:false
                })
                message.info(type === 'create'? '添加一笔数据成功!':'一笔数据修改完成!')
                this.requestList();
                this.userForm.props.form.resetFields()
            }
        })
    }

    handleGrant=()=>{
        let rows = this.state.selectedRows
        if (rows !==null && rows.length===1){
            let userId=rows[0].id
            let _this=this
            Promise.all([axios.ajax({
                url:'/cloud-long-upms/sysUser/loadRolesByUserId',
                method:'get',
                data:{
                    params:{
                        id:userId
                    }
                }
            }),axios.ajax({
                url:'/cloud-long-upms/sysRole/treeNodesRole',
                method:'get'
            })])
                .then(function (results) {
                    console.log(results)
                    let value=[]
                    results[0].data.roleList.forEach((item,index)=>{
                        value.push(item.id)
                    })
                    _this.setState({
                        grantData:results[0].data.roleList,
                        treeData:results[1].data.rows,
                        value:value,
                        isGrantVisible:true,
                        username:rows[0].name,
                        userId:rows[0].id
                    })
                })


        }else {
            Modal.warn({
                title:'警告',
                content:'请只选中一行!',
                okText:'确定'
            })
        }
    }

    grant=()=>{

        let roleIds=this.state.value.join(',')
        let _this=this
        axios.ajax({
            url:'/cloud-long-upms/sysUser/grantRole',
            method:'post',
            data:{
                params:{
                    userId:_this.state.userId,
                    roleIds:roleIds
                }
            }
        }).then((res)=>{
            if (res.status===200){
                message.success(`${res.message}`)
                this.setState({
                    isGrantVisible:false
                })
            }
        })
        // message.success("你点了OK:"+roleIds)

    }

    //查询提交
    filterSubmit = (fieldsValue)=>{
        if (fieldsValue && fieldsValue.createdatetimeStart){
            fieldsValue.createdatetimeStart=Utils.formatDate(fieldsValue.createdatetimeStart)
        }

        if (fieldsValue && fieldsValue.createdatetimeEnd) {
            fieldsValue.createdatetimeEnd=Utils.formatDate(fieldsValue.createdatetimeEnd)
        }
        this.params =Object.assign(this.params, fieldsValue)
        this.requestList()

    }
    requestList = () => {
        axios.requestList(this,'/cloud-long-upms/sysUser/page','get',this.params)
    }

    render(){

        const tProps = {
            treeData:this.state.treeData,
            value: this.state.value,
            onChange: this.onChange,
            treeCheckable: true,
            showCheckedStrategy: SHOW_PARENT,
            searchPlaceholder: '请选择',
            style: {
                width: 300,
            },
        }
        const selectedRowKeys = this.state.selectedRowKeys
        const rowCheckSelection = {
            type: 'checkbox',
            selectedRowKeys,
            // 单选框也可以用onChange onRow 适合单选
            onChange:(selectedRowKeys,selectedRows)=>{
                this.setState({
                    selectedRowKeys,
                    selectedRows
                })
            }
        }
        const columns=[
            {
                title:'id',
                dataIndex:'id'
            },
            {
                title: '用户名',
                dataIndex: 'name'
            },
            {
                title:'密码',
                dataIndex:'password',
                render:(text, record, index) => {
                    return '******'
                }
            },
            {
                title: '创建时间 ',
                dataIndex: 'createDateTime',
                render:Utils.formatDate
            },
            {
                title: '修改时间 ',
                dataIndex: 'modifyDateTime',
                render:Utils.formatDate
            }
        ]
        return (
            <div>
                <Card>
                    <BaseFilterForm filterSubmit={ this.filterSubmit } formList ={this.formList} />
                </Card>
                <Card style={{marginTop:10}}>
                    <Button type="danger" icon="delete" onClick={()=>this.handleOperator('delete')}>删除</Button>
                    <Button icon="plus" onClick={ ()=>this.handleOperator('create') }>增加</Button>
                    <Button icon="edit" onClick={()=>this.handleOperator('edit')}>编辑</Button>
                    <Button icon="edit" onClick={()=>this.handleGrant()}>授权</Button>
                </Card>

                <Table className="content-wrap"
                    bordered
                    rowSelection={rowCheckSelection}
                    columns={columns}
                    dataSource={this.state.dataSource}
                    pagination={this.state.pagination}
                />

                <Modal
                    title={ this.state.title }
                    visible={ this.state.isVisible }
                    onOk={ this.handleSubmit }
                    okText="确定"
                    width={ 600 }
                    onCancel={ () =>{
                        this.userForm.props.form.resetFields()
                        this.setState({
                            isVisible:false,
                            userInfo:''
                        })
                    }}
                    cancelText="取消"
                >
                    <UserForm userInfo ={ this.state.userInfo } type={ this.state.type } wrappedComponentRef={(inst) => this.userForm = inst }/>
                </Modal>

                <Modal
                    title="用户授权"
                    visible={this.state.isGrantVisible}
                    onOk={this.grant}
                    onCancel={()=>{
                        this.setState({
                            isGrantVisible:false
                        })
                        message.info('取消授权操作!')
                    }}
                    okText="确定"
                    cancelText="取消"
                >
                    <div>
                        <Tag><h4>当前授权用户:[{this.state.username}]</h4></Tag>
                    </div>
                    <Divider dashed />
                    <TreeSelect {...tProps} />
                </Modal>
            </div>
        )
    }
}
class UserForm extends React.Component{
    render(){
        const { getFieldDecorator } =this.props.form
        const userInfo = this.props.userInfo || {}
        const type = this.props.type
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 15}
        };
        return (
            <Form layout="horizontal">
                <Form.Item label="用户名" {...formItemLayout}>
                    {
                        userInfo && type ==='detail' ? userInfo.name:
                            getFieldDecorator('name',{
                                initialValue:userInfo.name,
                                rules:[
                                    {
                                        required:true,
                                        message:'用户名不能为空!'
                                    },
                                    {
                                        pattern:/^[a-zA-Z0-9_-]{4,16}$/, // new RegExp('^\\w+$','g')
                                        message:'用户必需为英文字母或数字下划线-!'
                                    }
                                ]
                            })(
                                <Input placeholder="请输入姓名" type="text"/>
                            )
                    }
                </Form.Item>
                <Form.Item label="密码" {...formItemLayout}>
                    {
                        userInfo && type ==='detail' ? userInfo.password:
                            getFieldDecorator('password',{
                                initialValue:userInfo.password,
                                rules:[
                                    {
                                        required:true,
                                        message:'密码不能为空!'
                                    },
                                    {
                                        min:5,max:36,
                                        message:'长度不在范围内!'
                                    }
                                ]
                            })(
                                <Input placeholder="请输入密码" type="text"/>
                            )
                    }
                </Form.Item>
            </Form>
        )
    }
}
UserForm = Form.create({})(UserForm)